package com.bdc.whatwhat.task;

import android.os.AsyncTask;

import com.bdc.whatwhat.Service.Service;
import com.bdc.whatwhat.factory.Factory;
import com.bdc.whatwhat.modele.WhatWhat;

/**
 * Created by florentchampigny on 25/06/14.
 */
public class FaireWhatWhatTask extends AsyncTask<Object, Void, WhatWhat> {

    public interface FaireWhatWhatTaskDelegate {
        public void faire(WhatWhat whatWhat);

        public void afficherChargement(boolean afficher);

        public void onWhatWhatEnvoye(WhatWhat whatWhat);

        public void onResultatVide();

        public void onErreurReseau();
    }

    FaireWhatWhatTaskDelegate delegate;
    boolean erreurReseau;
    boolean whatWhatExistant;

    public static final boolean EXISTANT = true;
    public static final boolean CREER = false;


    public FaireWhatWhatTask(FaireWhatWhatTaskDelegate delegate, boolean whatWhatExistant) {
        this.delegate = delegate;
        this.whatWhatExistant = whatWhatExistant;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if (delegate != null)
            delegate.afficherChargement(true);
    }

    @Override
    protected WhatWhat doInBackground(Object... objects) {

        WhatWhat whatWhat = null;

        String token = (String) objects[1];

        if (whatWhatExistant) {
            WhatWhat ww = (WhatWhat) objects[0];

            try {
                whatWhat = Service.envoyerWhatWhatExistant(ww.getId(), token);
            } catch (Service.NetworkException e) {
                erreurReseau = true;
                e.printStackTrace();
            }

        } else {

            String texte = (String) objects[0];

            try {
                whatWhat = Service.envoyerWhatWhat(texte, token);
            } catch (Service.NetworkException e) {
                erreurReseau = true;
                e.printStackTrace();
            }
        }

        return whatWhat;
    }

    @Override
    protected void onPostExecute(WhatWhat whatWhat) {
        super.onPostExecute(whatWhat);
        if (delegate != null) {
            delegate.afficherChargement(false);
            if (erreurReseau)
                delegate.onErreurReseau();
            else
                delegate.onWhatWhatEnvoye(whatWhat);
        }
    }
}
